const puppeteer = require('puppeteer');
const cheerio = require('cheerio');
const DeviceDescriptors = require('puppeteer/DeviceDescriptors');
const ua = DeviceDescriptors['iPhone 6'];
const path = require('path');
const resemble = require('resemblejs');
const fs = require('fs');
const Canvas = require('canvas');
const width = 750;
const height = 700;
const slider_width = 86;

const getTrack = distance => {
    let track = [];
    let current = 0;
    let mid = distance * 3.7 / 5;
    let t = 0.2 - Math.random()*0.05;
    let v = 0;

    while (current < distance) {
        if (current < mid) {
            a = 2 + Math.random();
        } else {
            a = -3 + Math.random();
        }
        let v0 = v;
        v = v0 + a * t;
        move = v0 * t + 1 / 2 * a * t * t;
        current += move;
        if (current > distance) {
          move = move - current + distance;
        }
        track.push(Math.round(move));
    }

    return track;
};

const sleep = duration => {
    return new Promise(resolve => {
        setTimeout(resolve, duration);
    });
};

(async () => {
    const browser = await puppeteer.launch({
        // executablePath: path.resolve(__dirname, '../Chromium.app/Contents/MacOS/Chromium'),
        headless: true,
        devtools: true,
        timeout: 5000,
        ignoreHTTPSErrors: true,
        args: [
            // '--proxy-server=127.0.0.1:8888', // Charles proxy
        ],
    });
    const page = await browser.newPage();
    await page.emulate(ua);

    await page.goto('https://aso100.com/error/ipLImit', {
        waitUntil: 'networkidle0',
        timeout: 30000,
    });

    page.screenshot({
        path: path.resolve(__dirname, 'test.png'),
        // quality: 50
    });
    const offset = await page.evaluate(() => {
        let offset_ifr = $('.gt_slider_knob.gt_show').offset();
        return {
            top: offset_ifr.top + 9,
            left: offset_ifr.left + 2,
        };
    });
    await page.screenshot({ path: 'screenshot2.png' });
    await page.mouse.move(offset.left + 10, offset.top + 10);
    // 按下鼠标
    await page.mouse.down({
        button: 'left',
    });

    await page.mouse.up({
        button: 'left',
    });
    // 等待图片出现
    await sleep(500);
    // 截图
    await page.screenshot({ path: 'screenshot3.png' });
    await new Promise(resolve => {
        resemble.outputSettings({
            transparency: 0,
        });
        resemble('screenshot2.png')
            .compareTo('screenshot3.png')
            .ignoreColors()
            .onComplete(data => {
                fs.writeFileSync('diff.png', data.getBuffer());
                resolve();
            });
    });
    const getDestinationX = min_x => {
        const canvas = new Canvas(width, height);
        const ctx = canvas.getContext('2d');
        const buf = fs.readFileSync('diff.png');
        const img = new Canvas.Image();
        img.src = buf;
        ctx.drawImage(img, 0, 0, width, height);
        const img_data = ctx.getImageData(0, 0, width, height).data;

        let destination_x = -1;

        for (let y = 0; y < height; y++) {
            for (let x = width; x >= min_x; x--) {
                let p = width * y + x;
                p = p << 2;
                if (img_data[p + 3] === 255 && img_data[p - 10 * 4 + 3] === 255) {
                    console.log(y);
                    destination_x = x;
                    break;
                }
            }
            if (destination_x > -1) break;
        }

        return destination_x - slider_width;
    };
    let track = getTrack(getDestinationX(285) /2);
    // await page.mouse.move(offset.left + 10, offset.top + 10);
    // 按下鼠标
    console.log(track)
    await page.mouse.down({
        button: 'left',
    });
    let move = 0;
    for (let index = 0; index < track.length; index++) {
      const x = track[index];
      offset.left +=x;
      move += x;
      await page.mouse.move( offset.left,  offset.top + Math.round(Math.random() * 2) - 4);
      // await sleep(2);
    }
    await page.mouse.up({
        button: 'left',
    });
})();